package com.luhuiguo.sso.web.pages;

import org.apache.commons.lang.StringUtils;
import org.apache.tapestry5.StreamResponse;
import org.apache.tapestry5.annotations.Component;
import org.apache.tapestry5.annotations.InjectPage;
import org.apache.tapestry5.annotations.OnEvent;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.corelib.components.BeanEditForm;
import org.apache.tapestry5.corelib.components.Form;
import org.apache.tapestry5.corelib.components.PasswordField;
import org.apache.tapestry5.corelib.components.TextField;
import org.apache.tapestry5.ioc.Messages;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.services.RequestGlobals;
import org.slf4j.Logger;

import com.luhuiguo.sso.entity.User;
import com.luhuiguo.sso.exception.UserExistsException;
import com.luhuiguo.sso.service.PropertyManager;
import com.luhuiguo.sso.service.UserManager;
import com.luhuiguo.sso.web.model.RegistrationInfo;
import com.luhuiguo.sso.web.util.RequestUtils;
import com.luhuiguo.tapestry.util.TextStreamResponse;

public class Registration {

	@Inject
	private Logger logger;

	@Inject
	private Messages messages;

	@Inject
	private RequestGlobals requestGlobals;

	@Inject
	private UserManager userManager;

	@Inject
	private PropertyManager propertyManager;

	@InjectPage
	private RegistrationSuccess registrationSuccess;

	@Component(id = "registrationForm")
	private BeanEditForm registrationForm;

	@Component(id = "username")
	private TextField usernameField;

	@Component(id = "password")
	private PasswordField passwordField;

	@Property
	private RegistrationInfo registrationInfo;

	private String baseURL;

	public String getBaseURL() {
		if (StringUtils.isEmpty(baseURL))
			try {
				baseURL = propertyManager.getBaseURL();
				if (StringUtils.isEmpty(baseURL))
					baseURL = RequestUtils.lookupDomainName(requestGlobals
							.getHTTPServletRequest());
			} catch (Exception e) {
				logger.warn(e.getMessage(), e);
			}
		return baseURL;
	}

	@OnEvent(value = "change" ,component = "username")
	public StreamResponse onChangeFromUsername(String username) {
		if (StringUtils.isNotBlank(username)) {
			if (!userManager.existsUser(username)) {
				String identifier = (new StringBuilder()).append(getBaseURL())
						.append("users/").append(username).toString();

				return new TextStreamResponse("text/html;charset=utf-8",
						identifier);
			} else {
				return new TextStreamResponse("text/html;charset=utf-8",
						messages.get("username-not-available"));
			}
		}

		return new TextStreamResponse("text/html;charset=utf-8", "");

	}

	@OnEvent(value = Form.VALIDATE_FORM, component = "registrationForm")
	void onValidateForm() {

		if (!StringUtils.equals(registrationInfo.getPassword(),
				registrationInfo.getConfirmPassword())) {
			registrationInfo.setPassword(null);
			registrationForm.recordError(passwordField, messages
					.get("password-mismatch"));
		}
		if (userManager.existsUser(registrationInfo.getUsername())) {
			registrationForm.recordError(usernameField, messages
					.get("username-not-available"));
		}
	}

	@OnEvent(value = Form.SUCCESS, component = "registrationForm")
	Object onSuccess() {
		try {
			User user = userManager.createUser(registrationInfo);
			return registrationSuccess.initialize(user);
		} catch (UserExistsException e) {
			registrationForm.recordError(usernameField, messages
					.get("username-not-available"));
		} catch (Exception e) {
			registrationForm.recordError(e.getMessage());
		}
		return null;
	}
}
